#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb
import MySQLdb.cursors
import codecs
import json

mysqlHost = "39.106.13.82"
mysqlUser = "root"
mysqlPwd =  "root"
mysqlDb = "jianjie"

def document_select_all():
    # 打开数据库连接
    db = MySQLdb.connect(mysqlHost, mysqlUser, mysqlPwd, mysqlDb, charset="utf8",
                         cursorclass=MySQLdb.cursors.DictCursor)
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()
    sql = "SELECT * FROM document2"
    try:
        cursor.execute(sql)
        result = cursor.fetchall()
        # for row in result:
            # unicode = row['title']
            # print(type(unicode), unicode)
            # str = unicode.encode('unicode-escape').decode('string_escape')
            # print(type(str), str.encode('utf-8'))
            # print('你好')
        return result
    except:
        print("Error: unable to fecth data")
        return []
    db.close()

def document_save_to_file():
    db = MySQLdb.connect(mysqlHost, mysqlUser, mysqlPwd, mysqlDb, charset="utf8",
                         cursorclass=MySQLdb.cursors.DictCursor)
    cursor = db.cursor()
    sql = "SELECT * FROM document2"
    try:
        print('读取数据库...')
        cursor.execute(sql)
        result = cursor.fetchall()
        file = codecs.open('document.json', 'wb', encoding='utf-8')
        file.write('[')
        for item in result:
            line = json.dumps(dict(item), ensure_ascii=False) + ',\n'
            file.write(line)
        file.write(']')
        print('数据保存到document.json文件中')
    except:
        print("Error: unable to fecth data")
    db.close()

def document_is_contains_title(title):
    # 打开数据库连接
    db = MySQLdb.connect(mysqlHost, mysqlUser, mysqlPwd, mysqlDb, charset="utf8",
                         cursorclass=MySQLdb.cursors.DictCursor)
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()
    sql = "SELECT * FROM document2"
    try:
        cursor.execute(sql)
        result = cursor.fetchall()
        for row in result:
            if row['title'] == title:
                return True
        return False
    except:
        print("Error: unable to fecth data")
        return False
    db.close()

document_select_all()
document_save_to_file()
